import socket
import os
import time

def receive_file(save_path, server_socket, file_name, total_size):
    file_path = os.path.join(save_path, file_name)
    # 检查文件夹是否存在
    if not os.path.exists(save_path):
        # 如果文件夹不存在，则创建文件夹
        os.makedirs(save_path)
        print(f"文件夹 {save_path} 已创建。")
    else:
        print(f"文件夹 {save_path} 已存在。")
    with open(file_path, 'wb') as file:
        received_size = 0
        while True:
            data = server_socket.recv(1024)
            if not data:
                break
            file.write(data)
            received_size += len(data)
            percent = (received_size / total_size) * 100 if total_size > 0 else 0
            print(f"\rReceiving {file_name}: {percent:.2f}%", end='')
        print()  # 新行

def start_client(host, port, save_path):
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((host, port))

    while True:
        print("Enter the number of the file or folder you want to access, or '../' to go up a directory, or 'ls' to list files and folders:")
        response = input()
        client_socket.sendall(response.encode('gbk'))  # 使用GBK编码发送客户端消息

        data = client_socket.recv(4096).decode('gbk')  # 使用GBK编码接收服务器消息
        if data.startswith("Invalid input"):
            print(data)
            continue
        files_and_folders = eval(data)
        if files_and_folders:
            print("Files and folders:")
            for i, (name, size) in enumerate(files_and_folders):
                print(f"{i}: {name} ({size:.2f} MB)")
            if response.isdigit():
                try:
                    index = int(response)
                    file_name, file_size_mb = files_and_folders[index]
                    file_size = int(file_size_mb * 1024 * 1024)
                    receive_file(save_path, client_socket, file_name, file_size)
                except IndexError:
                    print("Invalid selection.")
        elif response == "ls" and not files_and_folders:
            print("No files or folders to display.")
        else:
            print("No files or folders to display.")

    client_socket.close()

if __name__ == "__main__":
    start_client('cn-sz-yd-plustmp2.natfrp.cloud', 10620, './')